package com.winit.openapi.yanwen.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.oms.spi.isp.YanWenOrderService;
import com.winit.oms.spi.isp.command.vendor.yanwen.YanWenOrderLibraryCommand;
import com.winit.oms.spi.isp.command.vendor.yanwen.YanWenOrderStorageCommand;
import com.winit.oms.spi.isp.command.yanwen.YanWenReturnPackagesCommand;
import com.winit.oms.spi.isp.vo.YanWenOrder;
import com.winit.oms.spi.isp.vo.YanWenReturnPackagesVo;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;

@Controller
@RequestMapping(value = "/isp/yanwen")
public class YanWenController extends BaseController {

    private Logger             logger = LoggerFactory.getLogger(YanWenController.class);

    @Resource
    private YanWenOrderService yanWenOrderService;

    /**
     * 燕文入库接口
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/storage")
    public String warehousing(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validISPOrder(json);
            // 解析报文
            List<YanWenOrder> yanWenOrders = buildYanWenOrder(json);
            YanWenOrderStorageCommand storageCommand = new YanWenOrderStorageCommand();
            storageCommand.setYanWenOrder(yanWenOrders);
            yanWenOrderService.updateOrderStorage(storageCommand);

            // 入库时 计算成本
            // this.orderPayableMidCreate(orderNoList);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    /**
     * 燕文出库接口
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/library")
    public String library(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validISPOrder(json);

            // 解析报文
            List<YanWenOrder> yanWenOrders = buildYanWenOrder(json);
            YanWenOrderLibraryCommand libraryCommand = new YanWenOrderLibraryCommand();
            libraryCommand.setYanWenOrder(yanWenOrders);
            yanWenOrderService.updateOrderLibrary(libraryCommand);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    /**
     * 燕文退货接口
     * TODO Add comments here.
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/returnPackages")
    public String returnPackages(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            validReturnPackagesJson(json);
            YanWenReturnPackagesCommand command = this.buildReturnPackagesCommand(json);
            resultList = yanWenOrderService.updateOrderReturnPackages(command);
        }else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        if(resultList.size()>0){
            return JSONObject.toJSONString(resultList);
        }
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 0);
        map.put("msg", "成功");
        return JSONObject.toJSONString(map);

    }

    private void validReturnPackagesJson(JSONObject json) {
        if (json.containsKey("orderList")) {
            JSONArray list = json.getJSONArray("orderList");
            for (Object obj : list) {
                JSONObject jsons = (JSONObject) obj;
                ValidateUtil.validNotNull(jsons, "expressNo");
                ValidateUtil.validMaxLength(jsons, "expressNo", 60);
                ValidateUtil.validNotNull(jsons, "occurtime");
                ValidateUtil.validDateString(jsons, "occurTime", ValidateUtil.DATE_PATTERN_BASE);
                ValidateUtil.validNotNull(jsons, "remarkCode");
                ValidateUtil.validMaxLength(jsons, "remarkCode", 20);
                ValidateUtil.validMaxLength(jsons, "remark", 256);
            }
        }

    }

    /**
     * 验证参数
     * 
     * @param json
     */
    private void validISPOrder(JSONObject json) {
        if (json.containsKey("orderList")) {
            JSONArray packageList = json.getJSONArray("orderList");
            for (Object obj : packageList) {
                JSONObject pack = (JSONObject) obj;
                ValidateUtil.validNotNull(pack, "expressNo");
                ValidateUtil.validNotNull(pack, "occurtime");
                ValidateUtil.validMaxLength(pack, "expressNo", 60);
                ValidateUtil.validMaxLength(pack, "remark", 256);
                ValidateUtil.validMaxLength(pack, "orderCode", 32);
                ValidateUtil.validDateString(pack, "occurtime", ValidateUtil.DATE_PATTERN_BASE);
            }
        } else {
            logger.info("订单信息为空");
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "orderList");
        }
    }

    /**
     * 构建燕文订单
     * 
     * @param json
     * @return
     */
    private List<YanWenOrder> buildYanWenOrder(JSONObject json) {
        List<YanWenOrder> listOrders = new ArrayList<YanWenOrder>();
        YanWenOrder yanWenOrder = null;
        if (json.containsKey("orderList")) {
            JSONArray packageList = json.getJSONArray("orderList");
            for (Object obj : packageList) {
                JSONObject pack = (JSONObject) obj;
                yanWenOrder = new YanWenOrder();
                if (pack.containsKey("orderCode")) {
                    yanWenOrder.setOrderCode(pack.getString("orderCode").trim());
                }
                if (pack.containsKey("expressNo")) {
                    yanWenOrder.setExpressNo(pack.getString("expressNo").trim());
                }
                if (pack.containsKey("occurtime")) {
                    yanWenOrder.setOccurTime(pack.getDate("occurtime"));
                }
                if (pack.containsKey("weigth")) {
                    yanWenOrder.setWeigth(pack.getBigDecimal("weigth"));
                }
                if (pack.containsKey("height")) {
                    yanWenOrder.setHeight(pack.getBigDecimal("weigth"));
                }
                if (pack.containsKey("width")) {
                    yanWenOrder.setWidth(pack.getBigDecimal("width"));
                }
                if (pack.containsKey("length")) {
                    yanWenOrder.setLength(pack.getBigDecimal("length"));
                }
                if (pack.containsKey("remark")) {
                    yanWenOrder.setRemark(pack.getString("remark").trim());
                }
                listOrders.add(yanWenOrder);
            }
        }
        return listOrders;
    }

    private YanWenReturnPackagesCommand buildReturnPackagesCommand(JSONObject json) {
        YanWenReturnPackagesCommand command = new YanWenReturnPackagesCommand();
        List<YanWenReturnPackagesVo> yanWenReturnPackagesList = new ArrayList<YanWenReturnPackagesVo>();
        if (json.containsKey("orderList")) {
            JSONArray list = json.getJSONArray("orderList");
            for (Object obj : list) {
                YanWenReturnPackagesVo vo = new YanWenReturnPackagesVo();
                JSONObject jsons = (JSONObject) obj;
                if (jsons.containsKey("expressNo")) {
                    vo.setExpressNo(jsons.getString("expressNo").trim());
                }
                if (jsons.containsKey("occurtime")) {
                    vo.setOccurtime(jsons.getDate("occurtime"));
                }
                if (jsons.containsKey("remarkCode")) {
                    vo.setRemarkCode(jsons.getString("remarkCode").trim());
                }
                if (jsons.containsKey("remark")) {
                    vo.setRemark(jsons.getString("remark").trim());
                }
                yanWenReturnPackagesList.add(vo);
            }
            command.setYanWenReturnPackagesList(yanWenReturnPackagesList);
        }

        return command;
    }

}
